#include <cmath>

#include <co/dataIStream.h>
#include <co/dataOStream.h>

#include "objstate.h"

using namespace eqCommon;

static GLfloat3 const defaultLights[ObjState::lights_count] = {
    {-2, 0, 0},
    { 2, 0, 0}
};

eqCommon::ObjState::ObjState():
rotate(),
scale(),
position()
{
    rotate.x = 0;
    rotate.y = 0;
    
    scale = 1;
    
    position.x = 0;
    position.y = 0;
    position.z = -2;
    
    for(size_t i = 0; i < lights_count; ++i)
    {
        lights[i] = defaultLights[i];
        brightness[i] = 1.0f / lights_count;
    }
}

void eqCommon::ObjState::addRotate(GLfloat x, GLfloat y)
{
    GLfloat const pi = 360;
    rotate.x += x;
    rotate.y += y;
    rotate.x = std::fmod(rotate.x, pi);
    rotate.y = std::fmod(rotate.y, pi);
    if(rotate.x < 0)
        rotate.x += 2 * pi;
    if(rotate.y < 0)
        rotate.y += 2 * pi;
}

void eqCommon::ObjState::relativeMove(GLfloat x, GLfloat y, GLfloat z)
{
    position.x += x;
    position.y += y;
    position.z += z;
}

co::Object::ChangeType eqCommon::ObjState::getChangeType() const
{
    return INSTANCE;
}

void eqCommon::ObjState::getInstanceData(co::DataOStream& os)
{
    os << rotate.x << rotate.y;
    os << scale;
    os << position.x << position.y << position.z;
    for(size_t i = 0; i < lights_count; ++i)
        os << lights[i].x << lights[i].y << lights[i].z;
}

void eqCommon::ObjState::applyInstanceData(co::DataIStream& is)
{
    is >> rotate.x >> rotate.y;
    is >> scale;
    is >> position.x >> position.y >> position.z;
    for(size_t i = 0; i < lights_count; ++i)
        is >> lights[i].x >> lights[i].y >> lights[i].z;
}
